﻿'
' Copyright (c) 2010-2012, MatthiWare
'
' Permission is hereby granted, free of charge, to any person obtaining a
' copy of this software and associated documentation files (the "Software"),
' to deal in the Software without restriction, including without limitation
' the rights to use, copy, modify, merge, publish, distribute, sublicense,
' and/or sell copies of the Software, and to permit persons to whom the
' Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software. 
' You shall include 'MatthiWare' in the credits/about section of the program
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
' FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'

Imports SharpDX
Imports SharpDX.Direct2D1
Imports System.Threading
Imports TerrariaVB.Core.Helper

<Serializable()>
Public Class Block
    Inherits GameObjBase
    Implements IDisposable

    Public rect As DrawingRectangleF

    Private brightness As Single = 0 'neutral

    Private bufferedImage As Bitmap

    Private ReadOnly baseMiningTime As Int32 = 5
    Public miningTime As Int32 = 10
    Public timeBeingMined As Int32 = 0

    Private _bol As Boolean
    Public Property BlockLeft() As Boolean
        Get
            Return _bol
        End Get
        Set(ByVal value As Boolean)
            _bol = value
            'Init()
        End Set
    End Property

    Private _bob As Boolean
    Public Property BlockBottom() As Boolean
        Get
            Return _bob
        End Get
        Set(ByVal value As Boolean)
            _bob = value
            'Init()
        End Set
    End Property

    Public Shared Function GetSurroundingBlocks(b As Block, e As Core.Base.GameCoreEventArgs) As Block()
        Dim world As World = e.Core.Services.GetService(GetType(World))
        Dim blockList As New List(Of Block)()

        If ((b.Y - 1) >= 0) Then blockList.Add(world.level(b.X, b.Y - 1))
        If ((b.X + 1) < world.WorldWidth) Then blockList.Add(world.level(b.X + 1, b.Y))
        If ((b.Y + 1) < world.WorldHeight) Then blockList.Add(world.level(b.X, b.Y + 1))
        If ((b.X - 1) >= 0) Then blockList.Add(world.level(b.X - 1, b.Y))

        Return blockList.ToArray()
    End Function


    Private _bor As Boolean
    Public Property BlockRight() As Boolean
        Get
            Return _bor
        End Get
        Set(ByVal value As Boolean)
            _bor = value
            'Init()
        End Set
    End Property


    Private _bot As Boolean
    Public Property BlockTop() As Boolean
        Get
            Return _bot
        End Get
        Set(ByVal value As Boolean)
            _bot = value
            'Init()
        End Set
    End Property

    Public Sub New(pt As Point, sz As Size, info As BlockInfo)
        MyBase.New(pt, sz)
        Me.Info = info
        Me.miningTime = baseMiningTime + info.MiningBuff
        'Me.Init()
    End Sub

    Private _inf As BlockInfo
    Public Property Info() As BlockInfo
        Get
            Return _inf
        End Get
        Set(ByVal value As BlockInfo)
            _inf = value
        End Set
    End Property

    'Public Function GetGraphics(Optional clear As Boolean = True) As Graphics
    '    If (clear) Then bufferedImage = New Bitmap(Tile.TileSize, Tile.TileSize)

    '    Dim g As Graphics = Graphics.FromImage(bufferedImage)
    '    g.SmoothingMode = frmMain.SmoothingMode

    '    Return g
    'End Function

    Public Sub Init() 'might throw exception
        'making this sub thread safe

        'Monitor.Enter(Tile.DirtTileSet)
        'Try
        '    Dim g As Graphics = GetGraphics()
        '    Dim destRect As New Rectangle(0, 0, Tile.TileSize, Tile.TileSize)
        '    Dim srcRect As New Rectangle(Info.Id(0) * (Tile.TileSize + Tile.TileSetSpacing), Info.Id(1) * (Tile.TileSize + Tile.TileSetSpacing), Tile.TileSize, Tile.TileSize)

        '    Dim colorMatrixVal As Single()() = { _
        '   New Single() {1, 0, 0, 0, 0}, _
        '   New Single() {0, 1, 0, 0, 0}, _
        '   New Single() {0, 0, 1, 0, 0}, _
        '   New Single() {0, 0, 0, 1, 0}, _
        '   New Single() {brightness, brightness, brightness, 0, 1}}

        '    Dim colorMatrix As New ColorMatrix(colorMatrixVal)
        '    Dim ia As New ImageAttributes

        '    ia.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap)

        '    g.DrawImage(Tile.DirtTileSet, destRect, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel, ia)

        '    g.Dispose()

        'Finally
        '    Monitor.Exit(Tile.DirtTileSet)
        'End Try

    End Sub

    Public Overrides Sub Load(e As Core.Base.GameCoreEventArgs)
        MyBase.Load(e)
        Dim tSvc As Type = GetType(Zip)
        Dim svcContent As Zip = CType(e.Core.Services.GetService(tSvc), Zip)
        bufferedImage = Tile.DirtTileSet
    End Sub

    Public Overrides Sub Update(e As Core.Base.GameCoreEventArgs)
        MyBase.Update(e)


    End Sub

    Public Overrides Sub Draw(e As Core.Base.DrawEventArgs)
        MyBase.Draw(e)
        Try
            Dim svcPlayer As Player = e.Core.Services.GetService(GetType(Player))
            If (Not IsNothing(svcPlayer)) Then
                Dim c As Camera = svcPlayer.Cam
                Dim dstRect As New DrawingRectangleF(New Vector2((Me.X - c.X) * Tile.TileSize, (Me.Y - c.Y) * Tile.TileSize), New Vector2(Tile.TileSize))
                Dim srcRect As New DrawingRectangleF(Info.Id(0) * (Tile.TileSize + Tile.TileSetSpacing), Info.Id(1) * (Tile.TileSize + Tile.TileSetSpacing), Tile.TileSize, Tile.TileSize)
                e.Target.DrawBitmap(bufferedImage, dstRect, 1.0F, BitmapInterpolationMode.Linear, srcRect)

                rect = New DrawingRectangleF(CInt((Me.X - c.X) * Tile.TileSize), CInt((Me.Y - c.Y) * Tile.TileSize), CInt(Me.Width), CInt(Me.Height))
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Public Sub setBrightness(ByVal Brightness As Single)
    '    ' Brightness should be -1 (black) to 0 (neutral) to 1 (white)

    '    Me.brightness = Brightness
    '    Init()


    'End Sub

#Region "IDisposable Support"
    Private disposedValue As Boolean = False ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: dispose managed state (managed objects).
                If (Not IsNothing(bufferedImage)) Then
                    bufferedImage.Dispose()
                    bufferedImage = Nothing
                End If

            End If

            ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
            ' TODO: set large fields to null.
        End If
        Me.disposedValue = True
    End Sub

    ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
    Protected Overrides Sub Finalize()
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(False)
        MyBase.Finalize()
    End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

    Public Overrides Function ToString() As String
        Return String.Format("{0}{1}{2}{3}",
                             String.Format("Block Info: {0}", vbNewLine),
                             String.Format("> ID: {0,-15}{1} ({2})", "", Me.Info.Id(0), Me.Info.Id(1)),
                             String.Format("> Name: {0,-15}{1}", "", Me.Info.Name),
                             String.Format("> Location: {0,-15}({1}, {2})", Me.X, Me.Y)
                             )
    End Function

End Class
